package com.appbee.gdata.picasa.client.activity;

import javax.inject.Inject;

import com.appbee.core.client.place.HasPlace;
import com.appbee.core.client.place.PlaceControl;
import com.appbee.gdata.picasa.client.PicasaActivityModul;
import com.appbee.gdata.picasa.client.place.PhotoPlace;
import com.appbee.gdata.picasa.client.place.ThumbnailPlace;
import com.appbee.gdata.picasa.shared.SimplePhotoProxy;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.IsWidget;

public class PicasaPhotoActivity extends AbstractActivity
implements HasPlace
{
	public interface View extends IsWidget
	{
		void show(String photoUrl);

		void setActivity(PicasaPhotoActivity picasaPhotoActivity);

		void setPreviusEnabled(boolean enabled);

		void setNextEnabled(boolean enabled);
	}
	private PhotoPlace place;
	private final View view;
	private int index;
	private final PicasaPhotoDataProvider dataProvider;
	private final PlaceControl placeController;
	private SimplePhotoProxy photo;
	private final PicasaActivityModul activityModul;
	
	@Inject
	public PicasaPhotoActivity(	View view,
								PicasaActivityModul activityModul,
								PicasaPhotoDataProvider dataProvider,
								PlaceControl placeController)
	{
		super();
		this.view = view;
		this.activityModul = activityModul;
		this.dataProvider = dataProvider;
		this.placeController = placeController;
		view.setActivity(this);
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus)
	{
		index = dataProvider.findPhotoIndexById(place.getId());
		if(index>-1)
		{
			showPhoto();
		}
		else
		{
			view.setPreviusEnabled(false);
			view.setNextEnabled(false);
			view.show(place.getId());
		}
		panel.setWidget(view);
	}

	private void showPhoto()
	{
		view.setPreviusEnabled(index!=0);
		view.setNextEnabled((index+1)<dataProvider.getTotalsize() || !dataProvider.isExact());
		this.photo = dataProvider.getPhotoByIndex(index);
		view.show(photo.getUrl());
	}

	@Override
	public void setPlace(Place place)
	{
		this.place = (PhotoPlace) place;
	}

	public void doPrevius()
	{
		index--;
		showPhoto();
		setPlaceState();
	}

	public void doNext()
	{
		index++;
		showPhoto();
		setPlaceState();
	}

	private void setPlaceState()
	{
		placeController.setPlaceStateChange(new PhotoPlace(place.getAlbumId(),
				place.getName(), photo.getUrl()));
	}

	public void doBack()
	{
		placeController.goTo(new ThumbnailPlace(activityModul
				.getPhotosActivityId(), place
				.getAlbumId(), (index / 15) * 15));
	}

}
